<template>
  <div class="bi-chart">
    <!-- 数值指标 -->
    <div v-if="dataType === 'number'" class="number-metric">
      <div class="metric-title">{{ metricData.title }}</div>
      <div class="metric-value">{{ metricData.formattedValue }}{{ metricData.unit }}</div>
      <div v-if="metricData.compare" class="metric-compare">
        <span :class="['compare-rate', metricData.compare.changeType]">
          <el-icon v-if="metricData.compare.changeType === 'increase'"><TrendingUp/></el-icon>
          <el-icon v-if="metricData.compare.changeType === 'decrease'"><TrendingDown/></el-icon>
          {{ Math.abs(metricData.compare.changeRate || 0).toFixed(1) }}%
        </span>
        <span class="compare-text">较{{ compareText }}</span>
      </div>
      <div v-if="metricData.trend" class="metric-trend">
        {{ metricData.trend.trendDescription }}
      </div>
    </div>

    <!-- 图表 -->
    <div v-else-if="dataType === 'chart'" ref="chartEl" style="width: 100%; height: 400px;"></div>

    <!-- 表格 -->
    <div v-else-if="dataType === 'table'" class="table-container">
      <div class="table-header">
        <span class="table-title">{{ config?.chartName }}</span>
        <span class="table-total">共 {{ tableTotal }} 条记录</span>
      </div>

      <el-table
          :data="tableData"
          border
          style="width: 100%"
          v-loading="loading"
          :max-height="500"
      >
        <el-table-column
            v-for="column in tableColumns"
            :key="column.key"
            :prop="column.dataIndex"
            :label="column.title"
            :width="column.width"
            :align="column.align"
            show-overflow-tooltip
        />
      </el-table>

      <!-- 分页 -->
      <div class="table-pagination" v-if="tableTotal > 0">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="tableTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <el-icon class="is-loading">
        <Loading/>
      </el-icon>
      加载中...
    </div>

    <!-- 错误状态 -->
    <div v-if="error" class="error">
      <el-alert :title="error" type="error" show-icon/>
    </div>
  </div>
</template>

<script setup>
import {nextTick, onMounted, ref, watch} from 'vue'

import * as echarts from 'echarts'
import {biApi} from '@/api/bi.js'

const props = defineProps({
  chartId: {
    type: String,
    required: true
  },
  filters: {
    type: Object,
    default: () => ({})
  }
})

// 响应式数据
const chartEl = ref(null)
const dataType = ref('')
const metricData = ref({})
const tableData = ref([])
const tableColumns = ref([])
const tableTotal = ref(0)
const loading = ref(false)
const error = ref('')
const chartInstance = ref(null)
const compareText = ref('前期')
const isDevelopment = ref(import.meta.env.MODE === 'development')
const config = ref(null)


// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)

const loadData = async () => {
  loading.value = true
  error.value = ''

  try {
    // 如果是表格，传递分页参数
    const requestData = {
      chartId: props.chartId,
      filters: props.filters
    }

    if (dataType.value === 'table' || dataType.value === '') {
      requestData.page = currentPage.value
      requestData.pageSize = pageSize.value
    }

    const response = await biApi.getData(requestData)

    if (response.data.success) {
      handleData(response.data.data)
    } else {
      error.value = response.data.message
    }
  } catch (err) {
    error.value = '请求失败: ' + err.message
    console.error('数据加载错误:', err)
  } finally {
    loading.value = false
  }
}

const handleData = (data) => {
  console.log('接收到的数据:', data)

  // 判断数据类型
  if (data && data.formattedValue !== undefined) {
    // 数值类型
    dataType.value = 'number'
    metricData.value = data
    compareText.value = getCompareText(props.chartId)
  } else if (data && data.columns !== undefined && data.data !== undefined) {
    // 表格类型
    dataType.value = 'table'
    tableData.value = data.data || []
    tableColumns.value = data.columns || []
    tableTotal.value = data.total || 0
    currentPage.value = data.page || 1
    pageSize.value = data.pageSize || 20
  } else if (data && (data.xAxis || data.series)) {
    // 图表类型
    dataType.value = 'chart'
    nextTick(() => {
      renderChart(data)
    })
  } else {
    // 未知类型，尝试渲染为图表
    dataType.value = 'chart'
    nextTick(() => {
      renderChart(data)
    })
  }
}

// 分页处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  loadData()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadData()
}

const renderChart = (options) => {
  if (!chartEl.value) return

  if (!chartInstance.value) {
    chartInstance.value = echarts.init(chartEl.value)
  }

  chartInstance.value.setOption(options, true)
}

const getCompareText = (chartId) => {
  const map = {
    'total_sales': '去年同期',
    'user_count': '上月',
    'order_count': '上周',
    'conversion_rate': '上月'
  }
  return map[chartId] || '前期'
}

// 响应式监听
watch(() => props.filters, () => {
  currentPage.value = 1 // 重置到第一页
  loadData()
}, {deep: true})

// 监听图表ID变化
watch(() => props.chartId, () => {
  currentPage.value = 1 // 重置到第一页
  loadData()
})

onMounted(() => {
  // 加载配置信息
  loadConfig()
  loadData()
})

// 加载图表配置
const loadConfig = async () => {
  try {
    const response = await biApi.getConfig(props.chartId)
    if (response.data.success) {
      config.value = response.data.data
    }
  } catch (err) {
    console.error('加载配置失败:', err)
  }
}

</script>

<style scoped>
.table-container {
  margin-top: 16px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 0 8px;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.table-total {
  font-size: 14px;
  color: #666;
}

.table-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.bi-chart {
  position: relative;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.number-metric {
  text-align: center;
  padding: 20px;
}

.metric-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.metric-value {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
}

.metric-compare {
  font-size: 14px;
  margin-bottom: 8px;
}

.compare-rate {
  font-weight: 500;
}

.compare-rate.increase {
  color: #f56c6c;
}

.compare-rate.decrease {
  color: #67c23a;
}

.compare-text {
  color: #999;
  margin-left: 4px;
}

.metric-trend {
  font-size: 12px;
  color: #999;
}

.loading, .error {
  text-align: center;
  padding: 40px;
}

.table-container {
  margin-top: 16px;
}

.debug-tools {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1000;
}
</style>